package com.geo.geotool.service.trans;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.geo.geotool.entity.enmu.GeoFormatEnum;
import com.geo.geotool.mapper.PostGisMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * • @Description: TODO
 * • @author  : yell
 * • @date : 2021/12/14 09:58
 */
@Service
@Slf4j
public class CoordinateSystemTrans implements ICoordinateSystemTrans{
    @Autowired
    PostGisMapper postGisMapper;

    @Override
    public String coordinateSystemTrans(String sourceGeoJSON,String... targetSrId) throws Exception{
        String targetId = defaultTargetSrId;
        /**检测坐标系*/
        String jsonFormat = GeometryFormatCapture.capture(sourceGeoJSON);
        log.info("当前Geom格式:{}",jsonFormat);
        if(!jsonFormat.equals(GeoFormatEnum.GeoJSON.getType())){
            throw new Exception("坐标系转换失败:当前坐标格式不为GeoJSON,请先转换格式");
        }
        if(targetSrId!=null && targetSrId.length>0 && StringUtils.isNotEmpty(targetSrId[0])){
            targetId = targetSrId[0];
        }
        return trans(sourceGeoJSON,targetId);
    }
    private String trans(String sourceGeoJSON,String targetSrId) throws Exception {
        Object object = JSON.parse(sourceGeoJSON);
        if(object instanceof JSONArray){
            JSONArray resultArr = new JSONArray();
            for( int  i = 0  ; i < ((JSONArray) object).size() ; i++){
                JSONObject jo = coordinateSystemTrans(((JSONArray) object).getJSONObject(i),targetSrId);
                resultArr.add(jo);
            }
            return resultArr.toJSONString();
        }else {
            JSONObject jo = coordinateSystemTrans(((JSONObject) object),targetSrId);
            return jo.toJSONString();
        }
    }
    private JSONObject coordinateSystemTrans(JSONObject jsonObject,String targetSrId) throws Exception {
        String sourceSrId = jsonObject.getString("crs").replace("EPSG:","");
        GeometryFormatTrans geometryFormatTrans = new GeometryFormatTrans();
        String wkt = geometryFormatTrans.geoFormatTrans(jsonObject.toJSONString(),GeoFormatEnum.GeoJSON.getType(),GeoFormatEnum.WKT.getType());
        String transformGeoJSON = postGisMapper.transform(sourceSrId,targetSrId,wkt);
        /**转换为wkt*/
        log.info("转换后坐标:{}",transformGeoJSON);
        return JSONObject.parseObject(transformGeoJSON);
    }
}
